package com.lxx.interceptor;

import static com.lxx.utils.ResponseUtils.writeJson;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.lxx.common.ErrCode;

@Component
public class ExceptionHandler implements HandlerExceptionResolver{
	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		String params = recordParams(request);
		LOGGER.error("controller error, url : {}, params : {}", request.getRequestURI(), 
				params, exception);
		writeJson(response, ErrCode.ERROR);
		
		return null;
	}
	
	private String recordParams(HttpServletRequest request){
		StringBuffer sb = new StringBuffer();
		request.getParameterMap().forEach((k, v) -> {
			sb.append(k).append("=").append(Arrays.toString(v)).append(",");
		});
		if (sb.length() > 0) {
			sb.deleteCharAt(sb.length()-1);
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(JSON.toJSONString(ErrCode.ERROR.toMap()));
	}

}
